package com.zz.common.utils;

import com.zz.common.exception.TunnelException;
import lombok.extern.slf4j.Slf4j;

/**
 * 雪花算法工具类
 */
@Slf4j
public class SnowflakeUtil {


    // 自定义的起始时间戳，可以根据需要调整
    private static final long EPOCH = 1609459200000L; // 2021-01-01 00:00:00 UTC的时间戳，单位为毫秒

    // ID构成部分的位数
    private static final int WORKER_ID_BITS = 5;
    private static final int DATACENTER_ID_BITS = 5;
    private static final int SEQUENCE_BITS = 12;

    // 最大值
    private static final long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS); // 31
    private static final long MAX_DATACENTER_ID = ~(-1L << DATACENTER_ID_BITS); // 31
    private static final long MAX_SEQUENCE = ~(-1L << SEQUENCE_BITS); // 4095

    // 移位偏移量
    private static final int WORKER_ID_SHIFT = SEQUENCE_BITS;
    private static final int DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
    private static final int TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS;

    private final long workerId;
    private final long datacenterId;
    private long sequence = 0L;
    private long lastTimestamp = -1L;

    private final static SnowflakeUtil instance;

    static {
        instance = new SnowflakeUtil(1, 1);
    }

    private SnowflakeUtil(long workerId, long datacenterId) {
        if (workerId > MAX_WORKER_ID || workerId < 0) {
            throw new TunnelException(String.format("Worker ID can't be greater than %d or less than 0", MAX_WORKER_ID));
        }
        if (datacenterId > MAX_DATACENTER_ID || datacenterId < 0) {
            throw new TunnelException(String.format("Data Center ID can't be greater than %d or less than 0", MAX_DATACENTER_ID));
        }

        this.workerId = workerId;
        this.datacenterId = datacenterId;
    }

    private synchronized long nextId() {
        long timestamp = timeGen();

        if (timestamp < lastTimestamp) {
            // 时钟回拨处理：等待直到当前时间超过lastTimestamp
            log.info("Clock moved backwards. Refusing to generate id for {} milliseconds%n", lastTimestamp - timestamp);
            try {
                wait(lastTimestamp - timestamp + 1);
                timestamp = timeGen();
                if (timestamp < lastTimestamp) {
                    throw new TunnelException("Clock continued to move backwards after waiting. Last: %d, Current: %d", Long.toString(lastTimestamp), Long.toString(timestamp));
                }
            } catch (InterruptedException e) {
                throw new TunnelException(e.getMessage());
            }
        }

        if (lastTimestamp == timestamp) {
            // 同一毫秒内生成ID，则递增sequence
            sequence = (sequence + 1) & MAX_SEQUENCE;
            if (sequence == 0) {
                // 当前毫秒内的序列号已满，等待下一毫秒
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            // 不同毫秒内，重置sequence
            sequence = 0L;
        }
        lastTimestamp = timestamp;
        return ((timestamp - EPOCH) << TIMESTAMP_LEFT_SHIFT) |
                (datacenterId << DATACENTER_ID_SHIFT) |
                (workerId << WORKER_ID_SHIFT) |
                sequence;
    }

    private long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }
    private long timeGen() {
        return System.currentTimeMillis();
    }

    public static long genSnowflakeId() {
        return instance.nextId();
    }

}
